package com.ruoyi.shenji.controller;


import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.shenji.domain.ReciveData;
import com.ruoyi.shenji.domain.SysBhq;
import com.ruoyi.shenji.domain.TableData;
import com.ruoyi.shenji.domain.Vo.TableDataVo;
import com.ruoyi.shenji.service.SysBhqService;
import com.ruoyi.shenji.service.TableDataService;
import com.ruoyi.shenji.utils.DatabaseUtils;
import com.ruoyi.shenji.utils.FileUtils;
import com.ruoyi.shenji.utils.PingYinUtil;
import com.ruoyi.shenji.utils.GetMysqlSqlUtil;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.impl.SysRoleServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.controller.BaseController;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.core.domain.AjaxResult.success;
import static com.ruoyi.common.utils.PageUtils.startPage;

@Slf4j
@RestController
@RequestMapping("/shenji/table")
public class TableController extends BaseController {
    @Autowired
    private TableDataService tableDataService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private DatabaseUtils databaseUtils;

    @Autowired
    private SysBhqService sysBhqService;

    @PreAuthorize("@ss.hasPermi('system:table:list')")
    @GetMapping("/list")
    public AjaxResult list(TableData tableData) {
        LoginUser loginUser = getLoginUser();
        System.out.println(loginUser.getUser());
        String roleKey=tableDataService.getRoleKey(loginUser.getUser().getUserId());
        if("*".equals(roleKey)){
            System.out.println(tableDataService.selectList(tableData));
            return success(tableDataService.selectList(tableData));
        }else{
            List<TableDataVo> tableDataVoList = tableDataService.listWithAuth(tableData,roleKey);
            System.out.println(tableDataVoList);
            return success(tableDataVoList);
        }

    }


    /**
     * EasyPoi导入导出测试Controller
     * Created by macro on 2021/10/12.
     */
    @PostMapping("/importDataList")
    @ResponseBody
    public AjaxResult importMemberList(@RequestBody List<LinkedHashMap<String, Object>> data) {
        System.out.println(data);
        log.info("data:{}",data);
//        获取完整数据
        List<LinkedHashMap<String, Object>> resovedData = new ArrayList<>();
        TableData tableData = tableDataService.getById((Integer)data.get(0).get("tableId"));
        String roleKey = tableData.getRoleKey();
        String tableName = "";
        Integer flag = 0;
        Integer addFlag = 0;
        Integer delRepeatKey = 0;
        Integer parentId = tableData.getId();
        List<String> checkList = new ArrayList<>();
        Map<String,String> nameMap = new HashMap<>();
        List<TableData> checkIsAdd  = tableDataService.getByParentId(parentId.toString());
        if(checkIsAdd.size() > 0){
            addFlag = 1;
        }
        for (LinkedHashMap<String, Object> originalMap : data) {
            LinkedHashMap<String, Object> updatedMap = new LinkedHashMap<>();
            for (Map.Entry<String, Object> entry : originalMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                // 如果键是 "tableId"
                if (key.equals("tableId")) {
                    tableName =  tableDataService.getById((Integer)value).getAbbrev();
                } else {
                    if(flag.equals(0)){
                        // 否则，将键转换为拼音首字母，并更新键值对
                        String abbrevName = PingYinUtil.getFirstSpell(key);
                        if(checkList.contains(abbrevName)){
                            abbrevName = abbrevName+"_"+(delRepeatKey++) ;
                        }
                        nameMap.put(key,abbrevName);
                        if(addFlag == 0){
                            TableData insertData = new TableData(key,parentId,roleKey,abbrevName);
                            tableDataService.save(insertData);
                        }
                        checkList.add(abbrevName);
                    }

                    updatedMap.put(nameMap.get(key), value);
                }
            }
            if(flag.equals(0)){
                flag = 1;
            }
            resovedData.add(updatedMap);
        }


//       生成建表的sql
        String createTableSQL = GetMysqlSqlUtil.getCreateSql(resovedData.get(0),tableName);
        if(createTableSQL.equals("erro")){
            return AjaxResult.success("数据异常");
        }
        databaseUtils.executeCreate(createTableSQL);
        log.info("执行sql:{}",createTableSQL);


//      获取插入sql
        String insertTableSqlList = GetMysqlSqlUtil.getInsertSql(resovedData,tableName);
        databaseUtils.executeInsert(insertTableSqlList);
        log.info("执行sql:{}",insertTableSqlList);


        return success("导入成功");


//      放入最重要的表中

//        Set<String> keys = data.get(0).keySet();
//        List<String> checkKeyList = new ArrayList<>();
//        for (String name : keys) {
//            if(name.equals("tableId")){
//                continue;
//            }
//            String abbrevName = PingYinUtil.getFirstSpell(name);
//            if(checkKeyList.contains(abbrevName)){
//                abbrevName = PingYinUtil.getFullSpell(name);
//                if(checkKeyList.contains(abbrevName)){
//                    abbrevName = abbrevName+"_"+(delRepeatKey++) ;
//
//                }
//            }
//
//            // 在这里处理每个元素
//            System.out.println(name);
//        }

    };


    @GetMapping("/getDataById/{id}")
    public AjaxResult getDataById(@PathVariable("id")String id){

        LoginUser loginUser = getLoginUser();
        String roleKey=tableDataService.getRoleKey(loginUser.getUser().getUserId());
        return success(tableDataService.getByParentId(id));
    }

    @PutMapping("/add")
    public AjaxResult addNode(@RequestBody TableData tableData){
        LoginUser loginUser = getLoginUser();
        String roleKey=tableDataService.getRoleKey(loginUser.getUser().getUserId());
        if(roleKey.equals("*")){//管理员在操作
            if(!Objects.nonNull(tableData.getParentId())){//导入表头
                tableData.setParentId(0);
                tableData.setAncestors("0");
                roleKey = "gly";
            }else{
                String checkRoleKey = tableDataService.getById(tableData.getParentId()).getRoleKey();
                if(checkRoleKey.equals(roleKey)){//管理员在管理自己的表

                }else{//管理员在管理别人的表
                    roleKey = checkRoleKey;
                }
                String newAncestors = tableDataService.getAncestors(tableData,roleKey);
                tableData.setAncestors(newAncestors);
            }

        }else{//其他用户在管理表
            if(!Objects.nonNull(tableData.getParentId())){//导入表头
                TableData bhqTableData = new TableData();
                String name = sysRoleService.selectRoleByRoleKey(roleKey).getRoleName();
                bhqTableData.setName(name);
                bhqTableData.setParentId(0);
                bhqTableData.setAncestors("0");
                bhqTableData.setRoleKey(roleKey);
                bhqTableData.setAbbrev(roleKey);
                tableDataService.save(bhqTableData);
                tableData.setParentId(tableDataService.getByName(name,roleKey).getId());
            }
            String newAncestors = tableDataService.getAncestors(tableData,roleKey);
            tableData.setAncestors(newAncestors);
        }

        tableData.setRoleKey(roleKey);
        tableData.setAbbrev(roleKey+'_'+PingYinUtil.getFirstSpell(tableData.getName()));
        tableDataService.save(tableData);
        log.info("tableData:{}",tableData);
        return success("增加成功");
    }
    @PutMapping("/update")
    public AjaxResult updateNode(@RequestBody TableData tableData){
        log.info("tableData:{}",tableData);
        LoginUser loginUser = getLoginUser();
        String roleKey=tableDataService.getRoleKey(loginUser.getUser().getUserId());
        tableData.setRoleKey(roleKey);
        String newAncestors = tableDataService.getAncestors(tableData,roleKey);
        tableData.setAncestors(newAncestors);

        tableDataService.updateById(tableData);

        return success("修改成功");
    }

    @DeleteMapping("/delete/{id}")
    public AjaxResult deleteNode(@PathVariable String id){
        TableData tableData = tableDataService.getById(id);
        String tableName = tableData.getRoleKey()+'_'+PingYinUtil.getFirstSpell(tableData.getName());
        String dropTableSQL = GetMysqlSqlUtil.getDropSql(tableName);
        databaseUtils.executeDrop(dropTableSQL);
        log.info("删除{}表成功",tableName);
        tableDataService.removeById(id);
        log.info("删除{}表节点成功",tableName);
        List<Integer> ids = tableDataService.getByParentId(id).stream().map(item->{
            return item.getId();
        }).collect(Collectors.toList());
        tableDataService.removeByIds(ids);
        log.info("删除{}表子节点成功",tableName);
        return success("删除成功");
    }


    @GetMapping("/tableTree")
    public AjaxResult tableTree(TableData tableData){
        LoginUser loginUser = getLoginUser();
        String roleKey=tableDataService.getRoleKey(loginUser.getUser().getUserId());
        AjaxResult result = success(tableDataService.selectTableTreeList(tableData,roleKey));
        log.info("result:{}",result);
        return result;
    }

    @GetMapping("/data")
    public TableDataInfo getTableData(ReciveData reciveData) {
        startPage();
        log.info("reciveData:{}",reciveData);
        TableData tableData = tableDataService.getById(reciveData.getId());
        LoginUser loginUser = getLoginUser();
        String tableName = tableData.getAbbrev();
        List<TableData> tableKeyList = tableDataService.getByParentId(tableData.getId().toString());
        LinkedHashMap<String,Object> nameMap = tableDataService.getNameByAbbrevList(tableKeyList);
        String columnNames = tableKeyList.stream()
                .filter(data -> !data.getAbbrev().equals("bhqID"))
                .map(TableData::getAbbrev)
                .collect(Collectors.joining(","));
        columnNames = "id,"+columnNames;
        log.info("tableName:{}",tableName);
        log.info("result:{}",columnNames);
        Map<String ,Object> conditions = reciveData.getConditionsMap();
        String selectSQL = GetMysqlSqlUtil.getSelectSql(tableName,columnNames,conditions);
        List<LinkedHashMap<String, Object>> resultData =databaseUtils.executeSelect(selectSQL,reciveData.getPageNum(),reciveData.getPageSize());
        log.info("执行sql:{}",selectSQL);
        resultData.add(0,nameMap);
        log.info("resultData:{}",resultData);
        TableDataInfo tableDataInfo = getDataTable(resultData);
        tableDataInfo.setTotal(databaseUtils.executeTotalCount(selectSQL));
        return tableDataInfo;

    }

    @PostMapping("/addData")
    @ResponseBody
    public AjaxResult addData(@RequestBody LinkedHashMap<String,Object> tableData){
        log.info("tableData:{}",tableData);
        LoginUser loginUser = getLoginUser();
        String roleKey=tableDataService.getRoleKey(loginUser.getUser().getUserId());
        List<LinkedHashMap<String,Object>> tableDataList = new ArrayList<>();
        String tableName = tableDataService.getById((Integer)tableData.get("tableId")).getAbbrev();
        tableData.remove("tableId");
        tableDataList.add(tableData);
        String insertTableSqlList = GetMysqlSqlUtil.getInsertSql(tableDataList,tableName);
        databaseUtils.executeInsert(insertTableSqlList);
        log.info("执行sql:{}",insertTableSqlList);
        return success("增加成功");
    }

    @PutMapping("/updateData")
    @ResponseBody
    public AjaxResult updateData(@RequestBody Map<String,Object> tableData){
        log.info("tableData:{}",tableData);
        LoginUser loginUser = getLoginUser();
        String roleKey=tableDataService.getRoleKey(loginUser.getUser().getUserId());
        String tableName = tableDataService.getById((Integer)tableData.get("tableId")).getAbbrev();
        tableData.remove("tableId");

        String updateSql = GetMysqlSqlUtil.getUpdateSql(tableName,tableData);
        databaseUtils.executeInsert(updateSql);
        log.info("执行sql:{}",updateSql);
        return success("修改成功");
    }

    @DeleteMapping("/delData/{ids}")
    public AjaxResult delData(@PathVariable("ids") List<Integer> ids) {

        String tableName = tableDataService.getById(ids.get(0)).getAbbrev();
        ids.remove(0);
        String delSql = GetMysqlSqlUtil.getDeleteSql(tableName,ids);
        databaseUtils.executeDelete(delSql);
        log.info("执行sql:{}",delSql);
        return success("删除成功");
    }

    @PostMapping("/importTemplate/{id}")
    public void importTemplate(@PathVariable String id,HttpServletResponse response) {
        List<String> stringDataList = tableDataService.getByParentId(id).stream().map(item->{
            return item.getName();
        }).collect(Collectors.toList());
        FileUtils fileUtils = new FileUtils();
        fileUtils.importStringListToExcel(response, tableDataService.getById(id).getName(), stringDataList);
    }
}
